#ifndef __PROCESS_POOL_HPP__
#define __PROCESS_POOL_HPP__

#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <vector>
#include "Task.hpp"
// 先描述
class Channel
{
public:
    Channel(int fd, pid_t id) : _wfd(fd), _subid(id)
    {
        _name = "channel-" + std::to_string(_wfd) + "-" + std::to_string(id);
    }
    ~Channel()
    {
    }

    void Send(int code) // 发送
    {
        int n = write(_wfd, &code, sizeof(code));
        (void)n;
    }
    void Close() // 关闭
    {
        close(_wfd);
    }
    void Wait() // 等待
    {
        pid_t rid = waitpid(_subid, nullptr, 0);
        (void)rid;
    }
    int Fd()
    {
        return _wfd;
    }
    pid_t SubId()
    {
        return _subid;
    }
    std::string Name()
    {
        return _name;
    }

private:
    int _wfd;
    pid_t _subid;
    std::string _name;
};
// 在组织
class ChannelManager
{
public:
    ChannelManager() : _next(0)
    {
    }
    ~ChannelManager()
    {
    }
    void Insert(int wfd, pid_t subid) // 插入一个管道
    {
        _channels.emplace_back(wfd, subid);
    }
    Channel &Select() // 选择一个管道
    {
        auto &c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }
    void StopSubProcess() // 关闭管道
    {
        for (auto &channel : _channels)
        {
            channel.Close();
            std::cout << "关闭: " << channel.Name() << std::endl;
        }
    }
    void WaitSubProcess()
    {
        for (auto &channel : _channels) // 回收管道
        {
            channel.Wait();
            std::cout << "回收: " << channel.Name() << std::endl;
        }
    }
    void PrintChannel()
    {
        for (auto &channel : _channels)
        {
            std::cout << channel.Name() << std::endl;
        }
    }

private:
    std::vector<Channel> _channels;
    int _next; // 轮询分配任务
};

const int gdefaultnum = 5;

class ProcessPool
{
public:
    ProcessPool(int num) : _ProcessNum(num)
    {
        _tm.Register(PrintLog);
        _tm.Register(DownLoad);
        _tm.Register(UpLoad);
    }
    ~ProcessPool()
    {
    }
    void Work(int rfd) // 通过任务码来读取数据
    {
        while (true)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if (n > 0)
            {
                if (n != sizeof(code))
                {
                    continue;
                }
                std::cout << "子进程[" << getpid() << "]收到一个任务码" << code << std::endl;
                _tm.Execute(code);
            }
            else if (n == 0)
            {
                std::cout << "子进程退出！" << std::endl;
                break;
            }
            else
            {
                std::cout << "子进程读取失败！" << std::endl;
                break;
            }
        }
    }
    bool Start()
    {
        for (int i = 0; i < _ProcessNum; i++)
        {
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
                return false;
            pid_t subid = fork();
            if (subid < 0)
                return false;
            else if (subid == 0)
            {
                // child-read
                close(pipefd[1]);
                Work(pipefd[0]);
                close(pipefd[0]);
                exit(1);
            }
            else
            {
                // parent-write
                close(pipefd[0]);
                _cm.Insert(pipefd[1], subid);
            }
        }
        return true;
    }
    void Run()
    {
        // 选择一个任务
        int taskcode = _tm.Code();
        // 选择一个信道/子进程，负载均衡的选择子进程，完成任务
        auto &c = _cm.Select();
        std::cout << "选择了一个子进程" << c.Name() << std::endl;
        // 发送任务
        c.Send(taskcode);
        std::cout << "发送了一个任务码" << taskcode << std::endl;
    }
    void Stop()
    {
        _cm.StopSubProcess(); // 关闭父进程的所有wfd
        _cm.WaitSubProcess(); // 回收所有子进程的状态
    }
    void Debug()
    {
        _cm.PrintChannel();
    }

private:
    int _ProcessNum;
    ChannelManager _cm;
    TaskManger _tm;
};
#endif